package baseFx.common.caching.redis;

import baseFx.common.collections.redis.RedisMap;
import redis.clients.jedis.Jedis;

import java.util.Map;

public class RedisMapCache<V> extends RedisMap<V> {
    private long expireTime;
    private int expire;
    private String name;
    private Jedis jedis;

    public RedisMapCache(Jedis jedis, Class<V> clazz, String name, int expireSecond) {
        super(jedis, clazz, name);
        this.name = name;
        this.jedis = jedis;
        this.expire = expireSecond;
    }

    private void resetExpire() {
        if (expireTime > System.currentTimeMillis()) {
            return;
        }
        long value = jedis.ttl(name);
        if (value < 1) {
            jedis.expire(name, expire);
            value = expire;
        }
        this.expireTime = System.currentTimeMillis() + value * 1000;
    }

    @Override
    public V put(String key, V value) {
        V item = super.put(key, value);
        resetExpire();
        return item;
    }

    @Override
    public void putAll(Map<? extends String, ? extends V> m) {
        super.putAll(m);
        resetExpire();
    }
}
